package me.zhangjin.lucene.demo.queries;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class PhraseQueryTest {

    public static void main(String[] args) throws IOException {

        Path indexPath = Paths.get("indexdir/index");
        Directory dir = FSDirectory.open(indexPath);
        IndexReader reader = DirectoryReader.open(dir);
        IndexSearcher searcher = new IndexSearcher(reader);

        PhraseQuery.Builder builder = new PhraseQuery.Builder();
        // 2 和 3 分别表示短语的序号
        builder.add(new Term("title", "美国"), 2);
        builder.add(new Term("title", "总统"), 3);

        // 构建一个 PhraseQuery
        PhraseQuery phraseQuery = builder.build();

        // Query:title:"? ? 美国 总统"
        System.out.println("Query:" + phraseQuery);
        TopDocs tds = searcher.search(phraseQuery, 10);

        for (ScoreDoc sd : tds.scoreDocs) {
            Explanation explanation = searcher.explain(phraseQuery, sd.doc);
            System.out.println("explain:" + explanation + "\n");
            Document doc = searcher.doc(sd.doc);
            System.out.println("DocID:" + sd.doc);
            System.out.println("id:" + doc.get("id"));
            System.out.println("title:" + doc.get("title"));
            System.out.println("文档评分:" + sd.score);
        }
        dir.close();
        reader.close();
    }
}
